package com.wwh.furns.service.impl;

import com.wwh.furns.dao.FurnDAO;
import com.wwh.furns.dao.OrderDAO;
import com.wwh.furns.dao.OrderItemDAO;
import com.wwh.furns.dao.impl.FurnDAOImpl;
import com.wwh.furns.dao.impl.OrderDAOImpl;
import com.wwh.furns.dao.impl.OrderItemDAOImpl;
import com.wwh.furns.entity.*;
import com.wwh.furns.service.OrderService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author Albert
 * @date 2024/7/31-21:28
 * @describe
 */
public class OrderServiceImpl implements OrderService {
    OrderDAO orderDAO = new OrderDAOImpl();
    OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    FurnDAO furnDAO = new FurnDAOImpl();

    @Override
    public List<OrderItem> readOrderItemByOrderId(String orderId) {
        return orderItemDAO.readOrderItemByOrderId(orderId);
    }

    @Override
    public List<Order> readOrder(Integer memberId) {
        return orderDAO.readOrder(memberId);
    }

    @Override
    public String saveOrder(Cart cart, int memberId) {
        //创建订单编号，使用当前时间（毫秒级）和用户id生成
        String orderId = System.currentTimeMillis() + "" + memberId;
        //保存订单
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, memberId);
        orderDAO.saveOrder(order);

        HashMap<Integer, CartItem> items = cart.getItems();
        for (Integer id : items.keySet()) {
            //保存订单项
            CartItem cartItem = items.get(id);
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getPrice(), cartItem.getCount(), cartItem.getTotalPrice(), orderId);
            orderItemDAO.saveOrderItem(orderItem);

            //修改库存和销量
            Furn furn = furnDAO.queryFurnById(id);
            furn.setSales(furn.getSales() + cartItem.getCount());
            furn.setStock(furn.getStock() - cartItem.getCount());
            furnDAO.updateFurn(furn);
        }

        //清空购物车
        cart.clear();
        return orderId;
    }
}
